#include "Threadpool.h"
#include "WorkThread.h"
#include<unistd.h>
Threadpool::Threadpool(int threadNum, int queSize)
    : _threads(),
      _threadNum(threadNum),
      _queSize(queSize),
      _taskqueue(_queSize),
      is_Exit(false)
{
    _threads.reserve(_threadNum);
}
void Threadpool::start()
{
    for(int i =0;i<_threadNum;i++){
        //智能指针指向工作线程
        unique_ptr<Thread>up(new WorkThread(*this));
        //up是一个左值必须要转换成右值，才能存入容器中
        _threads.push_back(std::move(up));
    }
    for (auto &thread : _threads)
    {
        thread->start();
    }
}
void Threadpool::stop()
{
    //当任务队列不为空的时候等待一秒再退出
    while(!_taskqueue.empty()){
        sleep(1);
    }
    is_Exit = true;
    _taskqueue.wakeup();

    for (auto &thread : _threads)
    {
        thread->join();
    }
}
void Threadpool::addTask(Task && task){
    if(task){
        _taskqueue.push(task);
    }
}
void Threadpool::doTask(){
    while(!is_Exit){
        Task task = _taskqueue.pop();
        if(task){
            task();
        }
    }
}
